
#include "napi/native_api.h"
#include "client.h"
#include <cstdio>
static napi_value Add(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    double value0;
    napi_get_value_double(env, args[0], &value0);

    double value1;
    napi_get_value_double(env, args[1], &value1);

    napi_value sum;
    napi_create_double(env, value0 + value1, &sum);

    return sum;

}

static napi_value Mpv_create(napi_env env, napi_callback_info info)
{
//    size_t argc = 1;
//    napi_value args[1] = {nullptr};
////
//    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);
////
////    napi_valuetype valuetype0;
////    napi_typeof(env, args[0], &valuetype0);
////
////    napi_valuetype valuetype1;
////    napi_typeof(env, args[1], &valuetype1);
//
////    double value0;
////    napi_get_value_double(env, args[0], &value0);
////
////    double value1;
////    napi_get_value_double(env, args[1], &value1);
//
////    napi_value ctx=nullptr;
////    napi_create_double(env, 4, &sum);
//    mpv_handle *mpv;
//    mpv= mpv_create();
////    mpv_client_name(mpv); 
//    mpv_client_name(mpv);
////    printf("&s\n",&str);
////    napi_value str1={};
////    napi_create_string_utf8(env,mpv_client_name(mpv),1024,&str1);
//    napi_value sum;
//    napi_create_double(env, 4, &sum);
//    return sum;
    
    
    mpv_handle* mpv = mpv_create();
    
    napi_value result;
    if (mpv) {
        napi_create_string_utf8(env, mpv_client_name(mpv), NAPI_AUTO_LENGTH, &result);
        
        mpv_destroy(mpv);
//        napi_create_object(env, *result, mpv);
    } else {
        napi_create_string_utf8(env, "ERROR: mpv_create() failed", NAPI_AUTO_LENGTH, &result);
    }
    
    return result;

}

// 获取 mpv 版本信息
static napi_value GetMpvVersion(napi_env env, napi_callback_info info)
{
    unsigned version = mpv_client_api_version();
    
    napi_value result;
    napi_create_uint32(env, version, &result);
    
    return result;
}

static napi_value Mpv_init(napi_env env, napi_callback_info info)
{
    mpv_handle* mpv = mpv_create();
    
    napi_value result;
    if (mpv) {
        int ret = mpv_initialize(mpv);
        if (ret == MPV_ERROR_SUCCESS) {
            napi_create_string_utf8(env, "SUCCESS: mpv_initialize() worked", NAPI_AUTO_LENGTH, &result);
        } else {
            napi_create_string_utf8(env, "ERROR: mpv_initialize() failed", NAPI_AUTO_LENGTH, &result);
        }
        mpv_terminate_destroy(mpv);
    } else {
        napi_create_string_utf8(env, "ERROR: mpv_create() failed", NAPI_AUTO_LENGTH, &result);
    }
    
    return result;
}
//------------------------------------------------------------------------------------------

static mpv_handle *mpv_ctx = nullptr;



 static napi_value log_message_handler(void *ptr, mpv_log_level level, const char *txt) {
    // 你可以根据日志级别进行不同的处理，例如添加前缀、改变颜色等
    const char *level_str;
    switch (level) {
        case MPV_LOG_LEVEL_FATAL:   level_str = "FATAL";   break;
        case MPV_LOG_LEVEL_ERROR:   level_str = "ERROR";   break;
        case MPV_LOG_LEVEL_WARN:    level_str = "WARN";    break;
        case MPV_LOG_LEVEL_INFO:    level_str = "INFO";    break;
        case MPV_LOG_LEVEL_V:       level_str = "V";       break;
        case MPV_LOG_LEVEL_DEBUG:   level_str = "DEBUG";   break;
        case MPV_LOG_LEVEL_TRACE:   level_str = "TRACE";   break;
        default:                    level_str = "UNKNOWN"; break;
    }
    
    // 这里简单地将日志打印到标准错误输出
    // 在实际应用中，你可以写入文件、发送到网络等
    fprintf(stderr, "[mpv-%s] %s", level_str, txt);
    // 注意：`txt` 已经自带了换行符
}




// 初始化 mpv 实例
static napi_value InitMpv(napi_env env, napi_callback_info info) {
    
    size_t argc = 1;
    napi_value args[1];
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    
    // 创建 mpv 实例
    mpv_ctx = mpv_create();
    if (!mpv_ctx) {
        napi_throw_error(env, nullptr, "Failed to create mpv instance");
        return nullptr;
    }

    // 设置为纯音频模式
    mpv_set_option_string(mpv_ctx, "vid", "auto");
    
    mpv_set_option_string(mpv_ctx, "audio", "yes");
    
//    mpv_set_option(mpv_ctx, '', '');

    // 针对网络播放的优化参数
    // 设置网络缓存大小（单位：KB），减少卡顿
    mpv_set_option_string(mpv_ctx, "demuxer-max-bytes", "2048K"); // 例如设置为2MB
    mpv_set_option_string(mpv_ctx, "cache-secs", "10"); // 缓存秒数
    mpv_set_option_string(mpv_ctx,"vo","gpu");
    mpv_set_option_string(mpv_ctx,"gpu-context","openharmony");
    size_t str_size;
    napi_get_value_string_utf8(env, args[0], nullptr, 0, &str_size);
    char* surfaceId = new char[str_size + 1];
    napi_get_value_string_utf8(env, args[0], surfaceId, str_size + 1, &str_size);
    mpv_set_option_string(mpv_ctx,"wid",surfaceId);
    mpv_set_option_string(mpv_ctx,"openharmony-surface-size","854x480");
    mpv_request_log_messages(mpv_ctx,"v");
    
    // 初始化 mpv
    if (mpv_initialize(mpv_ctx) < 0) {
        napi_throw_error(env, nullptr, "Failed to initialize mpv");
        mpv_terminate_destroy(mpv_ctx);
        mpv_ctx = nullptr;
        return nullptr;
    }
    

//
//    napi_value result;
//    napi_get_boolean(env, true, &result);
//    return result;
    
    
    napi_value external;
    napi_status status = napi_create_external(env, 
        mpv_ctx, 
        [](napi_env env, void* finalize_data, void* finalize_hint) {
            // 当ArkTS侧对象被垃圾回收时，我们清理mpv实例
            mpv_handle* ctx = static_cast<mpv_handle*>(finalize_data);
            mpv_terminate_destroy(ctx);
        }, 
        nullptr, 
        &external);

    if (status != napi_ok) {
        napi_throw_error(env, nullptr, "Failed to create external object");
        mpv_terminate_destroy(mpv_ctx);
        return nullptr;
    }
    
//    mpv

    return external;
}

// 加载并播放音频文件
static napi_value PlayAudio(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value args[1];
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);

    // 从 JavaScript 参数获取音频文件路径
    size_t str_size;
    napi_get_value_string_utf8(env, args[0], nullptr, 0, &str_size);
    char* file_path = new char[str_size + 1];
    napi_get_value_string_utf8(env, args[0], file_path, str_size + 1, &str_size);

    // 构建 mpv 播放命令
    const char* cmd[] = {"loadfile", file_path, nullptr};
    mpv_command_async(mpv_ctx, 0, cmd); // 使用异步命令
    
    delete[] file_path;

    napi_value result;
    napi_get_boolean(env, true, &result);
    return result;
    
    
}

// 释放 mpv 资源
static napi_value ReleaseMpv(napi_env env, napi_callback_info info) {
    if (mpv_ctx) {
        mpv_terminate_destroy(mpv_ctx);
        mpv_ctx = nullptr;
    }
    napi_value result;
    napi_get_boolean(env, true, &result);
    return result;
}


static napi_value Pause(napi_env env, napi_callback_info info) {
//    if (mpv_ctx) {
//        mpv_terminate_destroy(mpv_ctx);
//        mpv_ctx = nullptr;
//    }
//    napi_value result;
//    napi_get_boolean(env, true, &result);
//    return result;
//      const char* cmd[]={'cycle','aaa',nullptr};
      const char* cmd[] = {"cycle", "pause", nullptr};
      mpv_command_async(mpv_ctx, 0, cmd);
}
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        { "add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "mpv_create", nullptr, Mpv_create, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "getv", nullptr, GetMpvVersion, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "mpv_init", nullptr, Mpv_init, nullptr, nullptr, nullptr, napi_default, nullptr },
        
        
        {"init_mpv", nullptr, InitMpv, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"play", nullptr, PlayAudio, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"release", nullptr, ReleaseMpv, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"pause", nullptr, Pause, nullptr, nullptr, nullptr, napi_default, nullptr},
        
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}
